package session

import (
	"encoding/json"
	"strings"
	"yuanxin-admin/internal/dto"

	"gitee.com/botaoshow/yuanxin/web/common/redis"
	"gitee.com/botaoshow/yuanxin/web/utils/tokens"
	"gitee.com/botaoshow/yuanxin/web/y"
	"github.com/gin-gonic/gin"
)

func GetUserInfo(g *gin.Context) *dto.LoginUserSessionDTO {
	//从session中获取用户信息
	tk := g.GetHeader("Authorization")
	if tk == "" {
		return nil
	}
	if strings.HasPrefix(tk, "Bearer ") {
		tk = tk[7:]
	}
	uc, err := tokens.ParseToken(tk)
	if err != nil {
		y.Error(err.Error())
		return nil
	}
	if uc == nil {
		return nil
	}
	shortToken := uc.ShortToken
	bytes, err := redis.Rdb.Get(g, "tokens:"+shortToken).Bytes()
	if err != nil {
		y.Error(err.Error())
		return nil
	}
	var u dto.LoginUserSessionDTO
	err = json.Unmarshal(bytes, &u)
	if err != nil {
		return nil
	}
	return &u
}

func GetUserId(g *gin.Context) string {
	info := GetUserInfo(g)
	if info == nil {
		return ""
	}
	return info.UserId
}
func GetUserName(g *gin.Context) string {
	info := GetUserInfo(g)
	if info == nil {
		return ""
	}
	return info.Username
}

func GetRoleCodes(g *gin.Context) []string {
	info := GetUserInfo(g)
	if info == nil {
		return []string{}
	}
	return info.Roles
}
